package com.jintian.smart.kernel.autoconfigure.model;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

public class ModelManager implements ApplicationContextAware, InitializingBean {
    @Resource
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.registerMapping();
    }

    private void registerMapping() {
        try {
            Method targetMethod = this.getClass().getDeclaredMethod("restartModel", String.class, HttpServletRequest.class, HttpServletResponse.class);
            RequestMappingInfo mapping_info = RequestMappingInfo.paths("/model/restart").methods(RequestMethod.GET).options(requestMappingHandlerMapping.getBuilderConfiguration()).build();
            requestMappingHandlerMapping.registerMapping(mapping_info, this, targetMethod);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ResponseEntity<String> restartModel(String name, HttpServletRequest request, HttpServletResponse response) {
        // TODO 需要安全机制
        if (this.applicationContext.getId().equals(name)) {
            return ResponseEntity.ok("不能重启主应用");
        }
        // TODO 多模块未迁移
//        try {
//            Model model = applicationContext.getBean("model$" + name, Model.class);
//            model.restart();
//            return ResponseEntity.ok("ok");
//        } catch (Exception ex) {
//            return ResponseEntity.internalServerError().body(ex.getMessage());
//        }
        return null;
    }
}
